import dayjs from "dayjs"
import Schema from 'validate'

const visitorValidate = new Schema({
  houseId: {
    required: true,
    message: '房屋信息不能为空！'
  },
  name: {
    type: String,
    match: /^\p{sc=Han}{2,6}$/u,
    message: '姓名不合法（2-6位中文名）'
  },
  mobile: {
    type: String,
    match: /^1[3-9]\d{9}$/,
    message: '手机号格式不正确'
  },
  visitDate: {
    required: true,
    message: '访问日期不能为空！'
  }
}, { strip: false })

Page({
  data: {
    dateLayerVisible: false,
    houseLayerVisible: false,
    houseList: [
      { name: '北京西三旗花园1号楼 101' },
      { name: '北京东村家园3号楼 302' },
      { name: '北京育新花园3号楼 703' },
      { name: '北京天通苑北苑8号楼 403' },
    ],
    currentDate: Date.now(),
    /** 3天以内的日期 */
    maxDate: dayjs(Date.now()).add(3, 'day').valueOf(),
    // maxDate: Date.now() + 1000 * 60 * 60 * 24 * 3,
    /** 选择的房屋信息 */
    houseInfo: '',
    // 性别
    gender: 0,
    // 房间id
    houseId: '',
    // 手机号
    mobile: '',
    // 姓名
    name: '',
    // 访问日期:3天以内的日期
    visitDate: '',
  },

  onLoad() {
    this.getHouseList()
  },

  /** 房屋列表信息 */
  async getHouseList() {
    let res = await wx.http({
      url: '/house',
    })

    /** name 格式转换 */
    let houseList = res.data.map((item) => {
      let name = item.name.replace(/(\d)(\d+)/, '$1号楼 $2室')
      return { id: item.id, name }
    })
    this.setData({
      houseList
    })
  },

  /** 选择房屋 */
  selectHouse(ev) {
    this.setData({
      houseId: ev.detail.id,
      houseInfo: ev.detail.name
    })
  },

  /** 选择访问日期 */
  visitDateConfirm(ev) {
    let visitDate = dayjs(ev.detail).format('YYYY-MM-DD')
    this.setData({
      visitDate,
      dateLayerVisible: false
    })
  },

  openHouseLayer() {
    this.setData({ houseLayerVisible: true })
  },
  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },
  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },
  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },

  /** 提交表单 */
  async onSubmit() {
    const { houseId, name, gender, mobile, visitDate } = this.data
    const params = { houseId, name, gender, mobile, visitDate }

    const errors = visitorValidate.validate(params)
    if (errors.length !== 0) {
      return wx.utils.toast(errors[0].message)
    }

    let res = await wx.http({
      url: '/visitor',
      method: 'post',
      data: params
    })
    if (res.code !== 10000) {
      return wx.utils.toast(res.message)
    }

    wx.showToast({
      title: '新增访客信息成功'
    })
    setTimeout(() => {
      wx.reLaunch({
        url: '/visitor_pkg/pages/passport/index',
      })
    }, 1500)

  },
})
